import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../common/index.dart';

class TimeCapsuleSentPage extends ConsumerStatefulWidget {
  const TimeCapsuleSentPage({super.key});

  @override
  ConsumerState<TimeCapsuleSentPage> createState() =>
      _TimeCapsuleSentPageState();
}

class _TimeCapsuleSentPageState extends ConsumerState<TimeCapsuleSentPage> {
  @override
  void initState() {
    super.initState();
    // 加载当前用户的时间胶囊
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadUserTimeCapsules();
    });
  }

  void _loadUserTimeCapsules() {
    final currentUser = ref.read(userProvider).currentUser;
    if (currentUser != null) {
      ref.read(timeCapsuleProvider.notifier).loadTimeCapsules(currentUser.id);
    } else {
      // 如果没有当前用户，清空时间胶囊列表
      ref.read(timeCapsuleProvider.notifier).clearTimeCapsules();
    }
  }

  @override
  Widget build(BuildContext context) {
    final timeCapsuleState = ref.watch(timeCapsuleProvider);

    // 监听用户状态变化，当用户登录状态改变时重新加载时间胶囊
    ref.listen<UserState>(userProvider, (previous, next) {
      if (previous?.currentUser?.id != next.currentUser?.id) {
        _loadUserTimeCapsules();
      }
    });
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        elevation: 0,
        leading: IconButton(
          onPressed: () {
            context.goBack();
          },
          icon: Icon(
            Icons.arrow_back_ios_new_rounded,
            color: Colors.white,
            size: 28.sp,
          ),
        ),
        backgroundColor: Colors.transparent,
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.sentBg),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: _buildBody(timeCapsuleState),
        ),
      ),
    );
  }

  Widget _buildBody(TimeCapsuleState state) {
    if (state.isLoading) {
      return Center(child: CircularProgressIndicator(color: Colors.white));
    }

    if (state.error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, color: Colors.white, size: 48.sp),
            SizedBox(height: 16.h),
            Text(
              'Error loading time capsules',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontFamily: 'PingFang SC',
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              state.error!,
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14.sp,
                fontFamily: 'PingFang SC',
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      );
    }

    if (state.timeCapsules.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(MyImages.timeCapsuleCover, width: 135.w, height: 135.h),
            SizedBox(height: 5.h),
            Text(
              'You Haven\'t Sent Any Letters Yet',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: 13.sp,
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w600,
                height: 1.23.h,
              ),
            ),
          ],
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.only(
        top: 100.h,
        left: 20.w,
        right: 20.w,
        bottom: 20.h,
      ),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 16.w,
          mainAxisSpacing: 20.h,
          childAspectRatio: 169 / 200, // 调整比例以适应图片和文字
        ),
        itemCount: state.timeCapsules.length,
        itemBuilder: (context, index) {
          final timeCapsule = state.timeCapsules[index];
          return _buildTimeCapsuleItem(timeCapsule);
        },
      ),
    );
  }

  Widget _buildTimeCapsuleItem(TimeCapsule timeCapsule) {
    return GestureDetector(
      onTap: () {
        // 跳转到时间胶囊详情页
        context.navigateTo('${AppRoutes.timeCapsuleDetail}/${timeCapsule.id}');
      },
      child: Column(
        children: [
          // 上部分：图片
          Container(
            width: 169.w,
            height: 169.h,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(8.r)),
            child: Stack(
              children: [
                // 背景图片
                Container(
                  width: 169.w,
                  height: 169.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    image: DecorationImage(
                      image: AssetImage(MyImages.timeCapsuleCover),
                      fit: BoxFit.contain,
                    ),
                  ),
                ),
                // 渐变遮罩
                Container(
                  width: 169.w,
                  height: 169.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withValues(alpha: 0.3),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 下部分：创建时间
          SizedBox(
            width: 169.w,
            child: Text(
              _formatDate(timeCapsule.createDate),
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: 13.sp,
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w600,
                decoration: TextDecoration.underline,
                decorationColor: Colors.white,
                height: 1.23.h,
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _formatDate(String dateString) {
    try {
      final date = DateTime.parse(dateString);
      final months = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December',
      ];
      return '${months[date.month - 1]} ${date.day}, ${date.year}';
    } catch (e) {
      return dateString;
    }
  }
}
